package com.wbw.ssb.service.impl;

import cn.hutool.core.date.DateUtil;
import com.wbw.ssb.common.api.ResultCode;
import com.wbw.ssb.dao.SmogDao;
import com.wbw.ssb.exception.ApiException;
import com.wbw.ssb.exception.Asserts;
import com.wbw.ssb.mbg.entity.Smog;
import com.wbw.ssb.mbg.mapper.SmogDynamicSqlSupport;
import com.wbw.ssb.mbg.mapper.SmogMapper;
import com.wbw.ssb.service.SmogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * @Author: guibo
 * @Description:
 * @Date: Created in 17:38 2021/5/25
 * @Modified By:
 */
@Service
public class SmogServiceImpl implements SmogService {
    @Autowired
    SmogDao smogDao;
    @Autowired
    SmogMapper smogMapper;
    @Override
    public LinkedHashMap<String, Double> getToday(Long granaryNumber) {
        LinkedHashMap<String,Double> dateDoubleHashMap = new LinkedHashMap<>();
        List<Smog>  smogList=  smogDao.getToday(granaryNumber);
        smogList.forEach(i->dateDoubleHashMap.put(DateUtil.formatDateTime(i.getDataTime()),i.getSmog()));
        return dateDoubleHashMap;
    }

    @Override
    public Smog getNow(Long granaryNumber) {
        Date twoMinuteAgo = new Date((new Date()).getTime()-120000);
        List<Smog> smogList =  smogMapper.select(c->c
                .where(SmogDynamicSqlSupport.granaryNumber,isEqualTo(granaryNumber))
                .and(SmogDynamicSqlSupport.dataTime,isGreaterThan(twoMinuteAgo))
                .orderBy(SmogDynamicSqlSupport.id.descending())
                .limit(1)
        );
        if (smogList.isEmpty()){
            return new Smog();
        }
        return smogList.get(0);
    }

}
